package com.aabte.lock.jedis.v1;

import com.aabte.lock.jedis.Constant;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.UUID;

public class RedisPessimisticLockTest {

    private JedisPool jedisPool;

    @Before
    public void before() throws IOException {

        InputStream in = RedisPessimisticLockTest.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties properties = new Properties();
        properties.load(in);

        String host = properties.getProperty(Constant.JedisConstant.REDIS_HOST);
        int port = Integer.parseInt(properties.getProperty(Constant.JedisConstant.REDIS_PORT));
        int maxTotal = Integer.parseInt(properties.getProperty(Constant.JedisConstant.REDIS_MAX_TOTAL));
        int maxIdle = Integer.parseInt(properties.getProperty(Constant.JedisConstant.REDIS_MAX_IDLE));
        int maxWaitMillis = Integer.parseInt(properties.getProperty(Constant.JedisConstant.REDIS_MAX_WAIT_MILLIS));

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);

        jedisPool = new JedisPool(config, host, port);
    }

    @After
    public void after(){
        jedisPool.close();
    }

    @Test
    public void testJedis(){
        Jedis jedis = jedisPool.getResource();
        String key = "Jedis";
        String value = "Hello Work!";
        jedis.set(key, value);
        String result = jedis.get(key);
        Assert.assertEquals(value, result);
        jedis.del(key);
        jedis.close();
    }

    @Test
    public void test(){

        String lockKey = "test_key_1";
        String requestId = UUID.randomUUID().toString();
        long expireTime = 10000;

        Thread thread1 = new ThreadTask(jedisPool.getResource(), lockKey, requestId, expireTime);
        Thread thread2 = new ThreadTask(jedisPool.getResource(), lockKey, requestId, expireTime);

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("主线程结束！");

    }
}
